package com.park.web.controller;

import com.park.web.base.baseOperation.BaseController;
import com.park.web.core.wrapper.WrapMapper;
import com.park.web.core.wrapper.Wrapper;
import com.park.web.model.domain.pbaOwnerOrganization;
import com.park.web.service.pbaOwnerOrganizationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

@RestController
@Api(value = "WEB - BasSystemUserController", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RequestMapping(value = "pbaOwnerOrganization", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class pbaOwnerOrganizationController extends BaseController {

    @Autowired
    pbaOwnerOrganizationService ipbaOwnerOrganizationService;

    @GetMapping("/selectAllTree")
    @ApiOperation(value = "递归所有节点树", notes = "递归所有节点树")
    public Wrapper selectAllTree() {
        var list = ipbaOwnerOrganizationService.selectAllTree(null);
        return WrapMapper.okWithoutMessage(list);
    }

    @GetMapping("/selectByParentOrgCode")
    @ApiOperation(value = "根据父节点查询所有子用户组织结构树", notes = "根据父节点查询所有子用户组织结构树")
    public Wrapper selectByOrgCode(String organizationCode) {
        var list = ipbaOwnerOrganizationService.selectByParentOrgCodeTree(organizationCode);
        return WrapMapper.okWithoutMessage(list);
    }

    @PostMapping("/Add")
    @ApiOperation(value = "添加用户自定义组织", notes = "添加用户自定义组织")
    public Wrapper Add(@RequestBody pbaOwnerOrganization entity) {
        String nextOrgCode = getOrgCode();
        while (ipbaOwnerOrganizationService.hasOrgCode(nextOrgCode)) {
            nextOrgCode = getOrgCode();
        }
        entity.setOrganizationCode(entity.getParentOrganizationCode() + "-" + nextOrgCode);
        ipbaOwnerOrganizationService.save(entity);
        return WrapMapper.ok(entity);
    }

    @GetMapping("/Del/{orgCode}")
    @ApiOperation(value = "删除用户自定义组织", notes = "删除用户自定义组织")
    public Wrapper Del(@PathVariable("orgCode") String orgCode) {
        ipbaOwnerOrganizationService.deleteByOrgCode(orgCode);
        return WrapMapper.ok();
    }

    private String getOrgCode() {
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String strNumber = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        int strIndex = random.nextInt(25);
        sb.append(str.charAt(strIndex));
        int numberIndex = random.nextInt(9);
        sb.append(strNumber.charAt(numberIndex));
        return sb.toString();
    }
}